﻿using Kingdee.BOS.App.Data;
using Kingdee.BOS.Core.Bill.PlugIn;
using Kingdee.BOS.Core.DynamicForm.PlugIn.Args;
using Kingdee.BOS.Orm.DataEntity;
using Kingdee.BOS.Util;
using LBKDHelper.Models;
using System;
using System.ComponentModel;

namespace LM.CB.K3Cloud.Plugin
{
    /// <summary>
    /// 作业数量维护表单插件
    /// </summary>
    /// <remarks>
    /// 功能：点击按钮“获取辅助车间作业”后，从生产入库单获取工艺路线信息，如果是辅助车间则获取工艺路线的所有作业活动数据。
    /// 创建人：鹿奔
    /// 创建日期：240718
    /// </remarks>
    [Description("作业数量维护表单插件"), HotUpdate]
    public class MaintainWorkBillPlugin : AbstractBillPlugIn
    {
        #region MyRegion

        /// <summary>
        /// 核算组织
        /// </summary>
        readonly ElementKeySchema FACCTGORGID = new ElementKeySchema
        {
            FormKey = "FACCTGORGID",
            DbKey = "FACCTGORGID",
            OrmKey = "ACCTGORGID"
        };

        /// <summary>
        /// 会计年度
        /// </summary>
        readonly ElementKeySchema FYEAR = new ElementKeySchema
        {
            FormKey = "FYEAR",
            DbKey = "FYEAR",
            OrmKey = "YEAR"
        };

        /// <summary>
        /// 会计期间
        /// </summary>
        readonly ElementKeySchema FPERIOD = new ElementKeySchema
        {
            FormKey = "FPERIOD",
            DbKey = "FPERIOD",
            OrmKey = "PERIOD"
        };

        /// <summary>
        /// 分录
        /// </summary>
        readonly ElementKeySchema FEntity = new ElementKeySchema
        {
            FormKey = "FEntity",
            DbKey = "T_CB_WORKACTIVEDATAENTRY",
            OrmKey = "CB_WORKACTIVEDATAENTRY"
        };

        /// <summary>
        /// 输出成本中心编码
        /// </summary>
        readonly ElementKeySchema FSRCCOSTCENTERID = new ElementKeySchema
        {
            FormKey = "FSRCCOSTCENTERID",
            DbKey = "FSRCCOSTCENTERID",
            OrmKey = "SRCCOSTCENTERID"
        };

        /// <summary>
        /// 作业活动
        /// </summary>
        readonly ElementKeySchema FWORKACTIVEID = new ElementKeySchema
        {
            FormKey = "FWORKACTIVEID",
            DbKey = "FWORKACTIVEID",
            OrmKey = "WORKACTIVEID"
        };

        /// <summary>
        /// 受益成本中心编码
        /// </summary>
        readonly ElementKeySchema FDESCOSTCENTERID = new ElementKeySchema
        {
            FormKey = "FDESCOSTCENTERID",
            DbKey = "FDESCOSTCENTERID",
            OrmKey = "DESCOSTCENTERID"
        };

        /// <summary>
        /// 数量
        /// </summary>
        readonly ElementKeySchema FQTY = new ElementKeySchema
        {
            FormKey = "FQTY",
            DbKey = "FQTY",
            OrmKey = "QTY"
        };

        /// <summary>
        /// 业务类型
        /// </summary>
        readonly ElementKeySchema FPROORDERTYPE = new ElementKeySchema
        {
            FormKey = "FPROORDERTYPE",
            DbKey = "FPROORDERTYPE",
            OrmKey = "PROORDERTYPE"
        };

        /// <summary>
        /// 订单编号
        /// </summary>
        readonly ElementKeySchema FPROORDERID = new ElementKeySchema
        {
            FormKey = "FPROORDERID",
            DbKey = "FPROORDERID",
            OrmKey = "PROORDERID"
        };

        /// <summary>
        /// 生产订单分录内码
        /// </summary>
        readonly ElementKeySchema FPROORDERENTRYID = new ElementKeySchema
        {
            FormKey = "FPROORDERENTRYID",
            DbKey = "FPROORDERENTRYID",
            OrmKey = "FPROORDERENTRYID"
        };

        /// <summary>
        /// 订单行号
        /// </summary>
        readonly ElementKeySchema FPROORDERSEQ = new ElementKeySchema
        {
            FormKey = "FPROORDERSEQ",
            DbKey = "FPROORDERSEQ",
            OrmKey = "FPROORDERSEQ"
        };

        /// <summary>
        /// 产品编码
        /// </summary>
        readonly ElementKeySchema FPRODUCTID = new ElementKeySchema
        {
            FormKey = "FPRODUCTID",
            DbKey = "FPRODUCTID",
            OrmKey = "PRODUCTID"
        };

        /// <summary>
        /// 生产车间
        /// </summary>
        readonly ElementKeySchema FWORKSHOPID = new ElementKeySchema
        {
            FormKey = "FWORKSHOPID",
            DbKey = "FWORKSHOPID",
            OrmKey = "FWORKSHOPID"
        };

        #endregion

        public override void BarItemClick(BarItemClickEventArgs e)
        {
            base.BarItemClick(e);

            if ("DEV_tbGETFZCJZY".EqualsIgnoreCase(e.BarItemKey))
            {
                GetData(e);
            }
        }

        private void GetData(BarItemClickEventArgs e)
        {
            // 清空老数据
            View.Model.DeleteEntryData(FEntity.FormKey);

            var org = Model.GetValue(FACCTGORGID.FormKey) as DynamicObject;
            string orgId = Convert.ToString(org["Id"]);
            string year = Convert.ToString(View.Model.GetValue(FYEAR.FormKey));
            string period = Convert.ToString(View.Model.GetValue(FPERIOD.FormKey));

            var sql = $@"/*dialect*/
            with 成本中心 as (
	            select *
	            from T_CB_COSTCENTER
	            where FBUSINESSTYPE = 5-- 辅助生产
            -- 	and FUSEORGID = @org
            )
            , 单据类型 as (
	            select a.FBILLTYPEID, b.FNAME as '单据类型名称'
	            from T_BAS_BILLTYPE as a
	            inner join T_BAS_BILLTYPE_L as b on b.FLOCALEID = 2052 and b.FBILLTYPEID = a.FBILLTYPEID
            )
            , 生产订单工艺路线 as (
	            select FEntryId as '生产订单分录内码', F_QLTK_COSTCENTER as '输出成本中心内码'
		            , F_QLTK_ZYHD as '作业活动内码', '耗用量' = sum(F_QLTK_QTY)
	            from QLTK_t_Route
	            group by FEntryId, F_QLTK_COSTCENTER, F_QLTK_ZYHD
	            having F_QLTK_ZYHD > 0
            )
            , 生产订单工艺路线Plus as (
	            select a.生产订单分录内码, b.FSEQ as '生产订单分录行号', c.FBILLNO as '生产订单编号'
		            , d.单据类型名称 as '生产订单类型名称', e.FNUMBER as '产品编码', a.输出成本中心内码
		            , a.耗用量, a.作业活动内码, b.FMATERIALID as '产品内码', h.FCOSTCENTERID as '受益成本中心内码'
		            , '产品数量' = isnull(f.F_DEV_CPSL, 1), c.FPRDORGID as '生产组织内码'
		            , b.FWORKSHOPID as '生产车间内码', '业务类型' = 'PO'-- 普通生产
		            , g.FENTRYID as '生产订单单据资料内码'
	            from 生产订单工艺路线 as a
	            inner join T_PRD_MOENTRY as b on b.FENTRYID = a.生产订单分录内码
	            inner join T_PRD_MO as c on c.FID = b.FID
	            inner join 单据类型 as d on d.FBILLTYPEID = c.FBILLTYPE
	            inner join T_BD_MATERIAL as e on e.FMATERIALID = b.FMATERIALID
	            left join DEV_t_ProcessRoute as f on f.FID = b.FROUTINGID
	            inner join T_CB_PROORDERTYPE as g on g.FFORMID = 'PRD_MO' and g.FPROORDERENTRYID = b.FENTRYID
	            inner join T_CB_COSTCENTER as h on h.FRELATIONTYPE = 'BD_Department' and h.FRELATION = b.FWORKSHOPID
            )
            , 生产入库单 as (
	            select a.FSID as '生产订单分录内码', d.FBASEPRDREALQTY as '入库数量'
                    , '入库年份' = year(c.FDATE), '入库月份' = month(c.FDATE)
                from T_PRD_INSTOCKENTRY_LK as a
                inner join T_PRD_INSTOCKENTRY as b on b.FENTRYID = a.FENTRYID
                inner join T_PRD_INSTOCK as c on c.FID = b.FID
                inner join T_PRD_INSTOCKENTRY_A as d on d.FENTRYID = b.FENTRYID
                where a.FSTABLENAME = 'T_PRD_MOENTRY'
            )
            , 总表 as (
	            select a.输出成本中心内码, a.作业活动内码, a.受益成本中心内码
		            , '数量' = a.耗用量 / a.产品数量 * c.入库数量
		            , a.业务类型, a.生产订单类型名称, a.生产订单分录行号, a.产品编码, a.生产订单分录内码
		            , a.产品内码, a.生产订单单据资料内码, a.生产车间内码
	            from 生产订单工艺路线Plus as a
	            inner join 成本中心 as b on b.FCOSTCENTERID = a.输出成本中心内码
	            inner join 生产入库单 as c on c.生产订单分录内码 = a.生产订单分录内码
	            where 1 = 1
                and a.生产组织内码 = {orgId}
                and c.入库年份 = {year} and c.入库月份 = {period}
	            and 1 = 1
            )

            select 输出成本中心内码, 作业活动内码, 受益成本中心内码, 生产订单分录内码,
                   sum(数量) as 数量,
                   MAX(业务类型) as 业务类型,
                   MAX(生产订单类型名称) as 生产订单类型名称,
                   MAX(生产订单分录行号) as 生产订单分录行号,
                   MAX(产品编码) as 产品编码,
                   MAX(产品内码) as 产品内码,
                   MAX(生产订单单据资料内码) as 生产订单单据资料内码,
                   MAX(生产车间内码) as 生产车间内码
            from 总表
            where 数量 > 0
            group by 输出成本中心内码, 作业活动内码, 受益成本中心内码, 生产订单分录内码;";

            var dataCollection = DBUtils.ExecuteDynamicObject(Context, sql);
            var entity = View.BusinessInfo.GetEntity(FEntity.FormKey);
            for (int i = 0, l = dataCollection?.Count ?? 0; i < l; i++)
            {
                var dataItem = dataCollection[i];

                Model.CreateNewEntryRow(entity, i);

                // 输出成本中心
                var cbzxId = Convert.ToInt32(dataItem["输出成本中心内码"]);
                View.Model.SetItemValueByID(FSRCCOSTCENTERID.FormKey, cbzxId, i);

                // 作业活动
                var activeId = Convert.ToInt32(dataItem["作业活动内码"]);
                View.Model.SetItemValueByID(FWORKACTIVEID.FormKey, activeId, i);

                // 受益成本中心
                var costCenterId = Convert.ToInt32(dataItem["受益成本中心内码"]);
                View.Model.SetItemValueByID(FDESCOSTCENTERID.FormKey, costCenterId, i);

                var workshopId = Convert.ToInt32(dataItem["生产车间内码"]);
                View.Model.SetItemValueByID(FWORKSHOPID.FormKey, workshopId, i);

                // 数量
                var qty = Convert.ToDecimal(dataItem["数量"]);
                View.Model.SetValue(FQTY.FormKey, qty, i);

                // 业务类型
                var bizType = Convert.ToString(dataItem["业务类型"]);
                View.Model.SetValue(FPROORDERTYPE.FormKey, bizType, i);

                var entryId = Convert.ToInt32(dataItem["生产订单分录内码"]);
                View.Model.SetItemValueByID(FPROORDERENTRYID.FormKey, entryId, i);

                var billNo = Convert.ToString(dataItem["生产订单单据资料内码"]);
                View.Model.SetItemValueByID(FPROORDERID.FormKey, billNo, i);

                var entrySeq = Convert.ToInt32(dataItem["生产订单分录行号"]);
                View.Model.SetItemValueByID(FPROORDERSEQ.FormKey, entrySeq, i);

                var productId = Convert.ToInt32(dataItem["产品内码"]);
                View.Model.SetItemValueByID(FPRODUCTID.FormKey, productId, i);
            }

            View.UpdateView(FEntity.FormKey);
        }
    }
}
